package com.hsnn.medstgmini.trading.catalog.dao.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.pro.base.model.BaseGoods;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.catalog.dao.PurHospCatalogDao;
import com.hsnn.medstgmini.trading.catalog.model.PurHospcatalog;
import com.hsnn.medstgmini.trading.catalog.model.PurHospcatalogLog;
import com.hsnn.medstgmini.trading.catalog.model.form.GoodsSelectForm;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;
import com.hsnn.medstgmini.util.PinYin;
@Repository("purHospCatalogDao")
public class PurHospCatalogDaoImpl implements PurHospCatalogDao {
	
	private static final Logger logger = LoggerFactory.getLogger(PurHospCatalogDaoImpl.class);
	
	@Autowired
	private HibernateSqlUtil dao;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	@Value("#{sysProp['system.isSetCatalogPrice']}")
	private boolean isSetCatalogPrice;
	@Value("#{sysProp['system.gzfjydel']}")
	private int gzfjydel;
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination getGoodsSelectList(Pagination page) {
		StringBuffer sqlHead = new StringBuffer()
		.append("select t.drug_code drugCode,t.qualityspec_name qualityspecName,t.form_name formName,")
		.append("t.spec_name specName,t.factor factor,t.unit_name unitName,t.material_name materialName,")
		.append("t.prod_compcode prodCompcode,t.prod_compname prodCompname,")
		.append("t.goods_code goodsCode,t.proj_name projName,t.pro_price_limit proPriceLimit,t.retail_price_limit retailPriceLimit,")
		.append("t.goods_source goodsSource,t.drug_attr drugAttr,t.is_longtime_plan isLongtimePlan,t.cat_comp_name catCompName ");
		Map<String, String> map = page.getConditions();
		StringBuffer sqlCondition = new StringBuffer()
		.append(" from base_goods_item t ")
		.append(" where t.proj_status=1 ")
		.append(" and SYSDATE() BETWEEN t.proj_starttime and t.proj_endtime")
		.append(" and t.qualityspec_status=1 and t.drug_status=1 ")
		.append(" and ")
		.append(AreaUtil.getDrugByArea(map.get("areaId"), "t.area_id"))
		.append(" and t.goods_code not in ")
		.append(" (select a.goods_code from pur_hospcatalog a where a.hosp_code=:hospCode)")
		.append(" and exists")
		.append(" (select * from bid_projhospital b where b.hosp_code=:hospCode and b.status=1 and b.proj_id=t.proj_id)")
		.append(" and (t.use_range = 0 or t.use_range = :userRange) and t.prod_compstatus=1 and t.status=1");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hospCode", page.getConditions().get("hospCode"));
		params.put("userRange", map.get("useRange"));
		
		if (StringUtils.isNotBlank(map.get("projId"))){
			sqlCondition.append(" and t.proj_id = :projId");
			params.put("projId", map.get("projId"));
		}
		if (StringUtils.isNotBlank(map.get("projName"))){
			sqlCondition.append(" and t.proj_name like :projName");
			params.put("projName","%" + map.get("projName").trim().toUpperCase() + "%");
		}
		if (StringUtils.isNotBlank(map.get("qualityspecName"))){
			sqlCondition.append(" and (t.qualityspec_name like :drugName or t.qualityspec_name_spel like :drugNameSpel)");
			params.put("drugName", "%" + map.get("qualityspecName").trim() + "%");
			params.put("drugNameSpel", "%" + map.get("qualityspecName").trim().toUpperCase() + "%");
		}
		if (StringUtils.isNotBlank(map.get("drugCode"))){
			sqlCondition.append(" and t.drug_code = :drugCode");
			params.put("drugCode", map.get("drugCode"));
		}
		if (StringUtils.isNotBlank(map.get("prodCompname"))){
			sqlCondition.append(" and (t.prod_compname like :compName or t.prod_compname_spel LIKE :compNameSpel)");
			params.put("compName", "%" + map.get("prodCompname").trim() + "%");
			params.put("compNameSpel", "%" + map.get("prodCompname").trim().toUpperCase() + "%");
		}
		if (StringUtils.isNotBlank(map.get("goodsSource"))){
			sqlCondition.append(" and t.goods_source = :goodsSource");
			params.put("goodsSource", map.get("goodsSource"));
		}

		//计算总记录数
		SQLQuery hospcataCountQuery =  getSession().createSQLQuery(" SELECT count(t.goods_code)  " + sqlCondition.toString());
		SQLQuery query =  getSession().createSQLQuery(sqlHead.append(sqlCondition).toString());
		if (params != null) {
			Iterator<?> list2 = params.entrySet().iterator();
			while (list2.hasNext()) {
				Map.Entry<String, ?> entry = (Map.Entry<String, ?>) list2.next();
				hospcataCountQuery.setParameter((String) entry.getKey(), entry.getValue());
				query.setParameter((String) entry.getKey(), entry.getValue());
			}
		}
		BigInteger all = (BigInteger) hospcataCountQuery.uniqueResult();
		page.setRecords (all.longValue());
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<?> list = query.list();
		page.setRows(list);
		return page;
	}
	public Pagination getDelCompList(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append(" SELECT")
		.append(" 	bp.comp_code compCode,")
		.append(" 	a.comp_name compName,")
		.append(" 	b.contact_name contactName,")
		.append(" 	b.contact_telephone contactTelephone")
		.append(" FROM")
		.append(" 	bid_projcompany bp")
		.append(" JOIN std_compinfo a ON a.comp_code = bp.comp_code and a.status=1")
		.append(" LEFT JOIN std_compinfo_detail b ON a.comp_id = b.comp_id")
		.append(" WHERE")
		.append(" 	bp. STATUS = 1")
		.append(" AND bp.proj_status = 1")
		.append(" AND SYSDATE() BETWEEN bp.proj_starttime")
		.append(" AND bp.proj_endtime")
		.append(" AND bp.proj_id = :projId ");
		Map<String, String> map = page.getConditions();
		Map<String, Object> params = new HashMap<String, Object>();
		if (null != map && map.size() > 0){
			params.put("projId", map.get("projId"));
			if (StringUtils.isNotBlank(map.get("compCode"))){
				sql.append(" and a.comp_code=:compCode");
				params.put("compCode", map.get("compCode").trim());
			}
			if (StringUtils.isNotBlank(map.get("compName"))){
				sql.append(" and (a.comp_name like :compName or a.comp_spel_code like :compName )");
				params.put("compName", "%"+map.get("compName")+"%");
			}
		}
		page = dao.getSqlPageMapList(sql.toString(), params, page);
		return page;
	}
	
	public Pagination saveGoodsSelect(Pagination page){
		Map<String, String> map = page.getConditions();
		PurHospcatalog data = new PurHospcatalog();
		data.setHospProCatId(UUID.randomUUID().toString());
		data.setHospCode(map.get("hospCode"));
		data.setGoodsCode(map.get("goodsCode"));
		data.setDelCompCode(map.get("delCompCode"));
		if (StringUtils.isNotBlank(map.get("proPrice"))){
			data.setProPrice(Double.valueOf(map.get("proPrice").trim()));
		}
		if (StringUtils.isNotBlank(map.get("proCount"))){
			data.setProCount(Integer.valueOf(map.get("proCount").trim()));
		}
		data.setStatus(Short.valueOf("1"));
		data.setUpdDatetime(new Date());
		data.setUpdUser(map.get("userId"));
		try {
			dao.add(data);
			save(data);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("医疗机构选择单条商品加入目录失败：",e);
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * 
	 *@category 加入目录
	 *@author 邱磊
	 *@date 2015年11月30日 下午1:47:36
	 *@param
	 */
	public void batchSaveGoodsSelect(List<GoodsSelectForm> list){
		if (list != null && list.size() > 0) {
			for (GoodsSelectForm info : list) {
				if (info != null) {
					StringBuffer sql = new StringBuffer()
					.append("insert into pur_hospcatalog (hosp_pro_cat_id,hosp_code,goods_code,del_comp_code,")
					.append(" pro_price,pro_count,status,bak_pur_count,upd_datetime,upd_user)")
					.append(" select :hospProCatId,:hospCode,a.goods_code,:delCompCode,:proPrice,:proCount,")
					.append(" :status,:bakPurCount,:updDatetim,:updUser from base_goods_item a ")
					.append(" where a.goods_code=:goodsCode")
					.append(" and a.goods_code not in")
					.append(" (select b.goods_code from pur_hospcatalog b where b.hosp_code=:hospCode)");
					Map<String, Object> params = new HashMap<String, Object>();
					String uuid = UUID.randomUUID().toString();
					params.put("hospProCatId", uuid);
					params.put("hospCode", info.getHospCode());
					params.put("delCompCode", info.getDelCompCode());
					params.put("proPrice", info.getProPrice());
					params.put("proCount", null);
					params.put("status", 1);
					params.put("bakPurCount", null);
					params.put("updUser", info.getUpdUser());
					params.put("goodsCode", info.getGoodsCode());
					params.put("updDatetim", new Date());
					dao.executeSql(sql.toString(), params);
					writeLogSql(uuid, 0);
				}
			}
		}
	}
	/**
	 * 
	 *@category 写医疗机构 目录日志
	 *@author 邱磊
	 *@date 2015年11月30日 下午1:38:26
	 *@param id:目录日志ID，updType:维护类型0：新增，1：修改
	 *@return void
	 */
	private void writeLogSql(String id,int updType){
		StringBuffer sql = new StringBuffer()
		.append("insert into pur_hospcatalog_log(log_id,hosp_pro_cat_id,hosp_code,goods_code,")
		.append(" del_comp_code,pro_price,pro_count,status,bak_pur_count,upd_type,upd_datetime,upd_user)")
		.append(" select UUID(),t.hosp_pro_cat_id,t.hosp_code,t.goods_code,t.del_comp_code,")
		.append(" t.pro_price,t.pro_count,t.status,t.bak_pur_count,:updType,t.upd_datetime,t.upd_user ")
		.append(" from pur_hospcatalog t where t.hosp_pro_cat_id=:hospProCatId");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("updType", updType);
		params.put("hospProCatId", id);
		dao.executeSql(sql.toString(), params);
	}
	
	/**
	 * 
	 *@category 医疗机构获取已勾选目录
	 *@author 邱磊
	 *@date 2015年7月7日 上午9:35:11
	 *@param page
	 *@return
	 */
	public Pagination getHaveSelectData(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append(" select b.hosp_pro_cat_id hospProCatId,")
		.append("  b.goods_code goodsCode,")
		.append("  b.pro_price proPrice,")
		.append("  b.del_comp_code delCompCode,")
		.append("  sc.comp_name delCompName,")
		.append("  b.status,")
		.append("  a.drug_code drugCode,")
		.append("  a.qualityspec_name qualityspecName,")
		.append("  a.form_name formName,")
		.append("  a.spec_name specName,")
		.append("  a.factor,")
		.append("  a.unit_name unitName,")
		.append("  a.material_name materialName,")
		.append("  a.prod_compname prodCompname,")
		.append("  a.drug_medicine drugMedicine,")
		.append("  a.proj_id projId,")
		.append("  a.proj_name projName,")
		.append("  a.pro_price_limit proPriceLimit,")
		.append("  a.retail_price_limit retailPriceLimit,")
		.append("  a.goods_source goodsSource,a.drug_attr drugAttr,")
		.append("  a.is_longtime_plan isLongtimePlan,")
		.append("  a.prod_compcode prodCompcode   ")
		.append(" from  pur_hospcatalog b inner join  base_goods_item a on a.goods_code=b.goods_code left join std_compinfo sc on sc.comp_code =b.del_comp_code  ")
		.append(" where  b.hosp_code=:hospCode  and a.proj_status=1  AND a.qualityspec_status = 1 and a.drug_status=1 and a.status=1 and SYSDATE() between a.proj_starttime and a.proj_endtime ");
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, String> map = page.getConditions();
		params.put("hospCode", map.get("hospCode"));
		if (StringUtils.isNotBlank(map.get("projId"))){
			sql.append(" and a.proj_id =:projId ");
			params.put("projId", map.get("projId"));
		}
		if (StringUtils.isNotBlank(map.get("projName"))){
			sql.append(" and a.proj_name like :projName ");
			params.put("projName", "%"+map.get("projName").trim().toUpperCase()+"%");
		}
		if (StringUtils.isNotBlank(map.get("goodsSource"))){
			sql.append(" and a.goods_source =:goodsSource ");
			params.put("goodsSource", map.get("goodsSource"));
		}
		if (StringUtils.isNotBlank(map.get("status"))){
			sql.append(" and b.status=:status");
			params.put("status", map.get("status").trim());
		}
		if (StringUtils.isNotBlank(map.get("drugCode"))){
			sql.append(" and a.drug_code =:drugCode ");
			params.put("drugCode", map.get("drugCode"));
		}
		if (StringUtils.isNotBlank(map.get("qualityspecName"))){
			if (PinYin.isPinYin(map.get("qualityspecName"))){
				sql.append(" and a.qualityspec_name_spel like :qualityspecName");
				params.put("qualityspecName", "%"+map.get("qualityspecName").trim().toUpperCase()+"%");
			} else {
				sql.append(" and a.qualityspec_name like :qualityspecName ");
				params.put("qualityspecName", "%"+map.get("qualityspecName").trim()+"%");
			}
		}
		if (StringUtils.isNotBlank(map.get("prodCompname"))){
			if (PinYin.isPinYin(map.get("prodCompname"))){
				sql.append(" and a.prod_compname_spel like :compName");
				params.put("compName", "%"+map.get("prodCompname").trim().toUpperCase()+"%");
			} else {
				sql.append(" and a.prod_compname like :compName ");
				params.put("compName", "%"+map.get("prodCompname").trim()+"%");
			}
		}
		
		if (StringUtils.isNotBlank(map.get("delComp"))){
			if (PinYin.isPinYin(map.get("delComp"))){
				sql.append(" and sc.comp_spel_code like :delComp");
				params.put("delComp", "%"+map.get("delComp").trim().toUpperCase()+"%");
			} else {
				sql.append(" and sc.comp_name like :delComp ");
				params.put("delComp", "%"+map.get("delComp").trim()+"%");
			}
		}
		sql.append(" order by b.upd_datetime desc,b.status desc");
		return dao.getSqlPageMapList(sql.toString(), params, page);
	}
	/**
	 * 
	 *@category 修改采购价和配送企业
	 *@author 邱磊
	 *@date 2015年7月7日 上午10:45:28
	 *@param form
	 */
	public void modifyPrice(GoodsSelectForm form){
		PurHospcatalog data = (PurHospcatalog) dao.getUniquerResult(PurHospcatalog.class, form.getHospProCatId());
		data.setProPrice(ParseNumber.toDouble(form.getProPrice()));
		data.setDelCompCode(form.getDelCompCode());
		dao.update(data);
		writeLog(data,Short.valueOf("1"));
	}
	/**
	 * 
	 *@category 批量启用停用
	 *@author 邱磊
	 *@date 2015年7月7日 下午2:31:19
	 *@param list
	 */
	@SuppressWarnings("unchecked")
	public void batchSwitchStatus(List<GoodsSelectForm> list){
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				GoodsSelectForm form = list.get(i);
				String sql = "update pur_hospcatalog set status=:status,upd_user=:updUser,upd_datetime=SYSDATE() where hosp_pro_cat_id=:id";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("status", form.getStatus());
				params.put("updUser", form.getUpdUser());
				params.put("id", form.getHospProCatId());
				dao.executeSql(sql, params);
				
				StringBuffer hql = new StringBuffer();
				hql.append("select goods_code,hosp_code from pur_hospcatalog where hosp_pro_cat_id = :id ");
				SQLQuery query = getSession().createSQLQuery(hql.toString());
				query.setString("id", form.getHospProCatId());
				query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
				List<Map<String,Object>> resultList = query.list();
				
				if ("0".equals(form.getStatus())){
					String dsql = "DELETE from pur_purplan where goods_code=:goodsCode and hosp_code=:hospCode";
					params.remove("status");
					params.remove("updUser");
					params.remove("id");
					params.put("goodsCode", resultList.get(0).get("goods_code").toString());
					params.put("hospCode",  resultList.get(0).get("hosp_code").toString());
					dao.executeSql(dsql, params);
				}
				writeLogSql(form.getHospProCatId(), 1);
			}
		}
	}
	/**
	 * 
	 *@category 批量修改采购价和配送企业
	 *@author 邱磊
	 *@date 2015年7月7日 下午2:29:47
	 *@param list
	 */
	public void batchModifyData(List<GoodsSelectForm> list, SysUser user){
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				GoodsSelectForm form = list.get(i);
				String sql = "update pur_hospcatalog set del_comp_code=:delCompCode,pro_price=:proPrice,upd_user=:updUser,upd_datetime=:updDatetime where hosp_pro_cat_id=:id";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("delCompCode", form.getDelCompCode());
				params.put("updUser", user.getId());
				params.put("id", form.getHospProCatId());
				params.put("proPrice", form.getProPrice());
				params.put("updDatetime", new Date());
				dao.executeSql(sql, params);
				String planSql = "update pur_purplan set del_comp_code=:delCompCode,pro_price=:proPrice,upd_datetime=:updDatetime,upd_user=:updUser where goods_code=:goodsCode and hosp_code=:hospCode";
				params.remove("id");
				params.put("goodsCode", form.getGoodsCode());
				HospInfo hosp = user.getInfo();
				params.put("hospCode", hosp.getHospCode());
				dao.executeSql(planSql, params);
				writeLogSql(form.getHospProCatId(), 1);
			}
		}
	}
	
	public void save(PurHospcatalog data) {
		dao.add(data);
		writeLog(data, (short)0);
	}
	public BaseGoods getBaseGoddsByCode(String goodsCode){
		return (BaseGoods) dao.getUniquerResult(BaseGoods.class, goodsCode);
	}
	
	private void writeLog(PurHospcatalog data, short status){
		PurHospcatalogLog log = new PurHospcatalogLog();
		log.setLogId(UUID.randomUUID().toString());
		BeanUtils.copyProperties(data, log);
		log.setUpdType(status);
		dao.add(log);
	}
	@Override
	public double getProPriceLimitByGoodsCode(String code) {
		 Object obj = getSession().createSQLQuery(" select pro_price_limit from base_goods_item where goods_code=:goodsCode ")
				 .setParameter("goodsCode", code).uniqueResult();
		 String temp =obj!=null?obj.toString():null;
		return  ParseNumber.toDouble(temp);
	}
	
	@Override
	public Pagination getDelCompListWithGoods(Pagination page) {
		HospInfo sh =(HospInfo)page.getForm();
		StringBuffer sql = new StringBuffer()
		.append(" SELECT")
		.append(" 	distinct t.del_comp_code compCode,")
		.append(" 	t.del_comp_name compName,")
		.append(" 	b.contact_name contactName,")
		.append(" 	b.contact_telephone contactTelephone")
		.append(" FROM")
		.append(" 	base_delrelationship t")
		.append(" JOIN std_compinfo a ON a.comp_code = t.del_comp_code and a.status=1")
		.append(" LEFT JOIN std_compinfo_detail b ON a.comp_id = b.comp_id")
		.append(" WHERE t.status=1 and (t.del_range = 0 or t.del_range=:delRange) and  t.area_code = :areaCode ")
		.append(" and t.goods_code=:goodsCode ");
		Map<String, String> map = page.getConditions();
		Map<String, Object> params = new HashMap<String, Object>();
		if (null != map && map.size() > 0){
			params.put("delRange", sh.getHospClassify());
			params.put("areaCode", sh.getArea().getAreaid());
			params.put("goodsCode",map.get("goodsCode"));
			
			if (StringUtils.isNotBlank(map.get("compCode"))){
				sql.append(" and t.del_comp_code=:compCode");
				params.put("compCode", map.get("compCode").trim());
			}
			if (StringUtils.isNotBlank(map.get("compName"))){
				sql.append(" and (t.del_comp_name like :compName or t.del_comp_name_spel like :compNameSpel )");
				params.put("compName", "%"+map.get("compName").trim()+"%");
				params.put("compNameSpel", "%"+map.get("compName").trim().toUpperCase()+"%");
			}
		}
		page = dao.getSqlPageMapList(sql.toString(), params, page);
		return page;
	
	}
	
	@Override
	public Pagination getDelCompListWithoutGoods(Pagination page) {
		StringBuffer sql = new StringBuffer()
		.append(" SELECT")
		.append(" 	distinct t.del_comp_code compCode,")
		.append(" 	t.del_comp_name compName,")
		.append(" 	b.contact_name contactName,")
		.append(" 	b.contact_telephone contactTelephone")
		.append(" FROM")
		.append(" 	base_delrelationship t")
		.append(" JOIN std_compinfo a ON a.comp_code = t.del_comp_code and a.status=1")
		.append(" LEFT JOIN std_compinfo_detail b ON a.comp_id = b.comp_id")
		.append(" WHERE t.status=1 and  t.prod_comp_code =:prodCompCode and t.hosp_code=:hospCode");
		Map<String, String> map = page.getConditions();
		Map<String, Object> params = new HashMap<String, Object>();
		if (null != map && map.size() > 0){
			params.put("prodCompCode",map.get("prodCompCode"));
			params.put("hospCode",map.get("hospCode"));
			if (StringUtils.isNotBlank(map.get("compCode"))){
				sql.append(" and t.del_comp_code=:compCode");
				params.put("compCode", map.get("compCode").trim());
			}
			if (StringUtils.isNotBlank(map.get("compName"))){
				sql.append(" and (t.del_comp_name like :compName or t.del_comp_name_spel like :compName )");
				params.put("compName", "%"+map.get("compName")+"%");
			}
		}
		page = dao.getSqlPageMapList(sql.toString(), params, page);
		return page;
	}
	
	/**
	 * @category 根据商品编码获取所有配送企业
	 * @author 韩守松
	 * @date   2015年12月8日
	 * @param  @param page
	 * @param  @return
	 */
	public Pagination getAllDelByGoodsCode(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append(" select ")
		.append(" distinct t.del_comp_code compCode,")
		.append(" t.del_comp_name compName, ")
		.append(" b.contact_name contactName, ")
		.append(" b.contact_telephone contactTelephone ")
		.append(" from base_delrelationship t ")
		.append(" left join std_compinfo a ON a.comp_code = t.del_comp_code and a.status=1 ")
		.append(" left join std_compinfo_detail b ON a.comp_id = b.comp_id")
		.append(" where t.status=1 and t.goods_code = :goodsCode ")
		.append(" and t.del_comp_code in ")
		.append(" (select m.del_comp_code from base_del_area_rel m where ");
		Map<String, String> map = page.getConditions();
		Map<String, Object> params = new HashMap<String, Object>();
		if(gzfjydel==1){
			sql.append(" m.area_code like :hospAreaCode) and t.area_code like :hospAreaCode ");
			params.put("hospAreaCode", map.get("areaCode").substring(0, 4)+"%");
		}else {
			sql.append(" m.area_code = :areaCode) ");
			params.put("areaCode", map.get("areaCode"));
		}
		
		if (null != map && map.size() > 0){
			if(StringUtils.isNotBlank(map.get("goodsCode"))){
				params.put("goodsCode", map.get("goodsCode").trim());
			}
			if (StringUtils.isNotBlank(map.get("compCode"))){
				sql.append(" and t.del_comp_code=:compCode");
				params.put("compCode", map.get("compCode").trim());
			}
			if (StringUtils.isNotBlank(map.get("compName"))){
				sql.append(" and (t.del_comp_name like :compName or a.comp_spel_code like :compName )");
				params.put("compName", "%"+map.get("compName")+"%");
			}
		}
		page = dao.getSqlPageMapList(sql.toString(), params, page);
		return page;
	}
	
	/**
	 * @category 保存新增的配送关系
	 * @author 韩守松
	 * @date   2015年12月8日
	 * @param  @param list
	 * @param  @param user
	 */
	@SuppressWarnings("unchecked")
	public void goodsWithDelSave(List<GoodsSelectForm> list, SysUser user){
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				GoodsSelectForm form = list.get(i);
				StringBuffer delHql = new StringBuffer();
				delHql.append(" select del_comp_name,del_comp_name_spel,del_comp_status from std_compinfo where comp_code = :compCode ");
				SQLQuery delQuery = getSession().createSQLQuery(delHql.toString());
				delQuery.setString("compCode", form.getDelCompCode());
				delQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
				List<Map<String,Object>> dellist = delQuery.list();
				
				StringBuffer hql = new StringBuffer();
				hql.append(" insert into base_delrelationship(del_rel_id,goods_code,del_comp_code,del_comp_name, ");
				hql.append(" del_comp_name_spel,del_comp_status,status,upd_user,upd_datetime ) ");
				hql.append(" values(　:del_rel_id , :goods_code , :del_comp_code , :del_comp_name , ");
				hql.append("  :del_comp_name_spel , :del_comp_status , 0 , :upd_user , :upd_datetime) ");
				SQLQuery query = getSession().createSQLQuery(hql.toString());
				query.setString("del_rel_id", UUID.randomUUID().toString());
				query.setString("goods_code", form.getGoodsCode());
				query.setString("del_comp_code", form.getDelCompCode());
				query.setString("del_comp_name", dellist.get(0).get("del_comp_name").toString());
				query.setString("del_comp_name_spel",dellist.get(0).get("del_comp_name_spel").toString() );
				query.setInteger("del_comp_status",Integer.valueOf(dellist.get(0).get("del_comp_status").toString()) );
				query.setString("upd_user",user.getId() );
				query.setDate("upd_datetime", new Date());
				query.executeUpdate();
				getSession().flush();
				getSession().clear();
			}
			}
	}
	
	
	/**
	 * @category 批量修改采购目录表配送企业
	 * @author lil
	 * @date   2015年12月13日
	 * @param  List<GoodsSelectForm> list
	 * @param  SysUser user
	 * @param  @return
	 */
	public void batchModifyCgmlZx(List<GoodsSelectForm> list, SysUser user){
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				GoodsSelectForm form = list.get(i);
				String sql = "update pur_hospcatalog set del_comp_code=:delCompCode,pro_price=:proPrice,upd_user=:updUser,upd_datetime=:updDatetime where hosp_pro_cat_id=:id";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("delCompCode", form.getDelCompCode());
				params.put("updUser", user.getId());
				params.put("id", form.getHospProCatId());
				params.put("proPrice", form.getProPrice());
				params.put("updDatetime", new Date());
				dao.executeSql(sql, params);
				writeLogSql(form.getHospProCatId(), 1);
			}
		}
	}
	
	/**
	 * @category 根据主键编号删除采购目录数据
	 * @author lil
	 * @date   2015年12月18日
	 * @param  List<GoodsSelectForm> list
	 * @param  @return
	 */
	public void deleteHospcatalog(List<GoodsSelectForm> list) {
		if (null != list && list.size() > 0){
			for (int i = 0; i < list.size(); i++){
				GoodsSelectForm form = list.get(i);
				String sql = "DELETE FROM pur_hospcatalog where hosp_pro_cat_id=:id and goods_code=:goods_code and hosp_code=:hosp_code";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("id", form.getHospProCatId());
				params.put("goods_code", form.getGoodsCode());
				params.put("hosp_code", form.getHospCode());
				dao.executeSql(sql, params);
				
				String sqlplan = "delete from pur_purplan where goods_code=:goods_code and hosp_code=:hosp_code";
				params.remove("id");
				dao.executeSql(sqlplan, params);
			}
		}
	}
}
